package cn.tristenstudy.blog.controller;

import cn.tristenstudy.blog.pojo.Blog;
import cn.tristenstudy.blog.pojo.vo.BlogQuery;
import cn.tristenstudy.blog.service.BlogService;
import cn.tristenstudy.blog.service.TagService;
import cn.tristenstudy.blog.service.TypeService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * @author xichen1.li
 * @date 2020-12-22 11:48
 */
@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TagService tagService;

    /**
     * 访问首页
     *
     * @param current 页码
     * @param model   model
     * @return 首页
     */
    @GetMapping("/")
    public String index(@RequestParam(required = false) Integer current, Model model) {
        if (current == null) {
            current = 1;
        }
        Page<Blog> page = blogService.listBlog(current);
        model.addAttribute("page", page);
        model.addAttribute("types", typeService.listTypeTop(6));
        model.addAttribute("tags", tagService.listTagTop(10));
        model.addAttribute("recommendBlogs", blogService.listRecommendBlogTop(8));
        model.addAttribute("first", page.hasPrevious());
        model.addAttribute("last", page.hasNext());
        return "index";
    }

    /**
     * 博客查询功能
     *
     * @param blogQuery 查询条件
     * @param current   页码
     * @param model     model
     * @return 查询结果页面
     */
    @PostMapping("/leeBlog/{current}/search")
    public String about(BlogQuery blogQuery, @PathVariable Integer current, Model model) {
        blogQuery.setCurrent(current);
        Page<Blog> page = blogService.listBlog(blogQuery);
        model.addAttribute("page", page);
        model.addAttribute("query", blogQuery.getQuery());
        model.addAttribute("first", page.hasPrevious());
        model.addAttribute("last", page.hasNext());
        return "search";
    }

    /**
     * 查看博客详情
     *
     * @param id    博客id
     * @param model model
     * @return 博客详情页面
     */
    @GetMapping("/leeBlog/blog/{id}")
    public String blog(@PathVariable("id") Long id, Model model) {
        Blog blog = blogService.selectById(id);
        model.addAttribute("blog", blog);
        return "blog";
    }

    /**
     * 查看关于我
     *
     * @param model model
     * @return 关于我页面
     */
    @GetMapping("/leeBlog/about")
    public String about(Model model) {
        return "about";
    }

    /**
     * 页面底部最新博客列表
     *
     * @param model model
     * @return 面底部最新博客列表
     */
    @GetMapping("/footer/blogs")
    public String footBlogs(Model model) {
        model.addAttribute("newblogs", blogService.listRecommendBlogTop(3));
        return "_fragments :: newbloglist";
    }

}
